package aar.test.tessocr.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.CabinetDetailsActivity;
import aar.test.tessocr.EventMessage.EventMessage;
import aar.test.tessocr.EventMessage.MessageEvent;
import aar.test.tessocr.ListofCabinetActivity;
import aar.test.tessocr.OrderListActivity;
import aar.test.tessocr.adapter.CabinetListAdapter;
import aar.test.tessocr.adapter.interfaces.OnItemClickListener;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabinetListMpdel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.view.CustomLoadingMoreFooter;
import aar.test.tessocr.view.SearchHistoryPopwindow;
import butterknife.BindView;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;
import static okgo.utils.HttpUtils.runOnUiThread;

/**
 * Created by sunshine on 2020/7/23.
 */

public class CabinetListFragment extends BaseFragment implements XRecyclerView.LoadingListener{
    @BindView(R.id.rv_data)
    XRecyclerView rvData;
    @BindView(R.id.tv_no_data)
    TextView tv_no_data;
    @BindView(R.id.et_fragment_search)
    TextView etFragmentSearch;
    @BindView(R.id.view_line)
    View viewLine;

    private List<CabinetListMpdel> mList = new ArrayList<>();
    private CabinetListAdapter mAdapter;
    private boolean isFirst = true;
    private int pageNum = 1;
    private String search = "";

    public static CabinetListFragment newInstance() {
        return new CabinetListFragment();
    }

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.fragment_cabinet_list);
    }

    @Override
    protected void setUpView(View view) {

    }

    @Override
    protected void setUpComponent() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rvData.setLayoutManager(manager);
        mAdapter = new CabinetListAdapter(getActivity(), mList, false);
        rvData.setAdapter(mAdapter);
        final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(getActivity());
        rvData.setFootView(footer, new CustomFooterViewCallBack() {
            @Override
            public void onLoadingMore(View yourFooterView) {
                footer.onLoadingMore();
            }

            @Override
            public void onLoadMoreComplete(View yourFooterView) {
                footer.onLoadMoreComplete();
            }

            @Override
            public void onSetNoMore(View yourFooterView, boolean noMore) {
                footer.onSetNoMore();
            }
        });
        rvData.setPullRefreshEnabled(true);
        rvData.setLoadingMoreEnabled(true);
        rvData.setLoadingListener(this);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = null;
                intent = new Intent(getActivity(), CabinetDetailsActivity.class);
                intent.putExtra("cabinetName", mList.get(position).getCabinetname());
                intent.putExtra("cabinetId", mList.get(position).getCabinetid());
                startActivity(intent);
            }

            @Override
            public void onItemClick(String date, int weekday) {
            }
        });

        etFragmentSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SearchHistoryPopwindow(getActivity(), search, false, (SearchHistoryPopwindow.OnSearchListener) getActivity(), "cabinetSearchContent").showAtLocation(viewLine, Gravity.TOP, 0, 0);
            }
        });
    }

    @Override
    protected void setUpData() {
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));
        map.put("page", pageNum);
        map.put("size", ConstantPara.PAGESIZE);
        map.put("keyword", search);

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<CabinetListMpdel>>>post(Urls.URL_CAB_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CabinetListMpdel>>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CabinetListMpdel>>> response) {
                        if (pageNum == 1) {
                            mList.clear();
                        }

                        if (null != response.body().data) {
                            mList.addAll(response.body().data);
                        }

                        if (null == mList || mList.size() == 0) {
                            tv_no_data.setVisibility(View.VISIBLE);
                        } else {
                            tv_no_data.setVisibility(View.GONE);
                        }

                        if (null == response.body().data || response.body().data.size() == 0) {
                            mAdapter.notifyDataSetChanged();

                            rvData.refreshComplete();
                            rvData.loadMoreComplete();
                            rvData.setNoMore(true);
                        } else {
                            if (null != response.body().data && response.body().data.size() > 0) {
                                rvData.refreshComplete();
                                pageNum++;
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CabinetListMpdel>>> response) {
                        if (pageNum == 1) {
                            tv_no_data.setVisibility(View.VISIBLE);
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        }
                        rvData.refreshComplete();
                        rvData.loadMoreComplete();
                        rvData.setNoMore(true);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(EventMessage eventMsg) {
        String msg = eventMsg.getMessage();
        if (msg.equals("refreshCabinetList")) {
           refreshData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void search(MessageEvent eventMsg) {
        if (eventMsg.getType() == 1) {
            search = eventMsg.getMessage();
            etFragmentSearch.setText(search);
            pageNum = 1;
            getData();
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (isFirst) {
            isFirst = false;
            refreshData();
        }
    }

    private void refreshData() {
        pageNum = 1;
        getData();
    }

    /*@Override
    public void onSearch(String searchContent) {
        search = searchContent;
        etFragmentSearch.setText(search);
        pageNum = 1;
        getData();
    }

    @Override
    public void onBack() {

    }*/
}
